package com.ckerchina.admin.ckadmin.utils;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 字符串工具类
 *
 */
public class StringUtils {
	
	public static boolean isEmpty(String str) {
		return !isNotEmpty(str);
	}
	
	public static boolean isNotEmpty(String str) {
		return str!= null && str.trim().length() != 0;
	}
	
	/**
	 * 验证是否为数字组成的字符串,不包含空字符串与浮点型数值
	 *	@param str
	 *	@return
	 */
	public static boolean isNumeric(String str) {
        if (isEmpty(str)) {
            return false;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if (Character.isDigit(str.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }
	public static boolean isBigDecimal(String str){ 
		try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
	}
	

	/** 对传入的字符串str进行Html encode转换 */
	public static String filter(String str) {
	    if(str ==null || str.trim().equals("")){
	    	return str;
	    }
	    StringBuilder encodeStrBuilder = new StringBuilder();
	    for (int i = 0, len = str.length(); i < len; i++) {
	       encodeStrBuilder.append(htmlEncode(str.charAt(i)));
	    }
	    return encodeStrBuilder.toString();
	}
	
	private static String htmlEncode(char c) {
	    switch(c) {
	       case '&':
	           return"&amp;";
	       case '<':
	           return"&lt;";
	       case '>':
	           return"&gt;";
	       case '"':
	           return"&quot;";
	       case ' ':
	           return"&nbsp;";
	       default:
	           return c +"";
	    }
	}
	
	public static HashMap<String,String> getValue(Object thisObj) {
		HashMap<String,String> map = new HashMap<String,String>();
		Class c;
		try {
			c = Class.forName(thisObj.getClass().getName());
			Method[] m = c.getMethods();
			for (int i = 0; i < m.length; i++) {
				String method = m[i].getName();
				if (method.startsWith("get")) {
					try {
						Object value = m[i].invoke(thisObj);
						if (value != null) {
							String key = method.substring(3);
							key = key.substring(0, 1).toLowerCase()
									+ key.substring(1);
							map.put(key, String.valueOf(value));
						}
					} catch (Exception e) {
						System.out.println("error:" + method);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
}
